import guaxiang from "./data.js";
// 64卦完整数据
const hexagrams = [
  {
    id: 1,
    name: "乾为天",
    upper: "乾",
    lower: "乾",
    description: "乾上乾下",
    text: "元亨利贞。",
    yaoTexts: [
      "初九：潜龙勿用。",
      "九二：见龙在田，利见大人。",
      "九三：君子终日乾乾，夕惕若厉，无咎。",
      "九四：或跃在渊，无咎。",
      "九五：飞龙在天，利见大人。",
      "上九：亢龙有悔。",
    ],
    yaoPattern: [1, 1, 1, 1, 1, 1],
  },
].concat(...guaxiang);
// 获取DOM元素
const manualBtn = document.getElementById("manual-btn");
const autoBtn = document.getElementById("auto-btn");
const buttonContainer = document.getElementById("button-container");
const manualForm = document.getElementById("manual-form");
const resultContainer = document.getElementById("result-container");
const cancelManualBtn = document.getElementById("cancel-manual");
const submitManualBtn = document.getElementById("submit-manual");
const newCalculateBtn = document.getElementById("new-calculate");
const guaInfo = document.getElementById("gua-info");
const guaText = document.getElementById("gua-text");

// 初始化显示水火既济卦
document.addEventListener("DOMContentLoaded", () => {
  const defaultHexagram = hexagrams.find((h) => h.id === 1) || hexagrams[0];
  // 更新卦象显示
  updateGuaByPattern(defaultHexagram.yaoPattern);
  // 更新卦名和卦辞
  updateGuaInfo(defaultHexagram);
});

// 手动输入按钮点击事件
manualBtn.addEventListener("click", () => {
  buttonContainer.classList.add("hidden");
  manualForm.classList.remove("hidden");
  manualForm.classList.add("animate-fade-in");
});

// 取消手动输入
cancelManualBtn.addEventListener("click", () => {
  manualForm.classList.add("hidden");
  buttonContainer.classList.remove("hidden");
});

// 提交手动输入
submitManualBtn.addEventListener("click", () => {
  // 获取用户选择的爻象 (从上到下)
  const yaoValues = [];
  for (let i = 6; i >= 1; i--) {
    const selectedYao = document.querySelector(`input[name="yao${i}"]:checked`);
    if (!selectedYao) {
      alert(`请选择第${i}爻`);
      return;
    }
    yaoValues.push(selectedYao.value === "yang" ? 1 : 0);
  }

  // 根据爻象查找对应的卦
  const hexagram = findHexagramByPattern(yaoValues);

  // 显示结果区域
  manualForm.classList.add("hidden");
  resultContainer.classList.remove("hidden");

  // 更新卦象显示
  updateGuaByPattern(yaoValues);

  // 更新卦名和卦辞
  updateGuaInfo(hexagram);
});

// 自动卜算按钮点击事件
autoBtn.addEventListener("click", () => {
  buttonContainer.classList.add("hidden");

  // 显示加载动画
  const loadingHTML = `
        <div class="w-full flex flex-col items-center justify-center py-12">
            <div class="animate-spin rounded-full h-16 w-16 border-4 border-primary/30 border-b-primary mb-4"></div>
            <p class="text-gray-600 text-lg">正在进行随机卜算...</p>
            <p class="text-gray-400 text-sm mt-2">此过程模拟掷铜钱，静心等待片刻</p>
        </div>
    `;
  resultContainer.innerHTML = loadingHTML;
  resultContainer.classList.remove("hidden");

  // 模拟三枚铜钱掷爻的过程
  simulateCoinTossing();
});

// 重新卜算按钮点击事件
newCalculateBtn.addEventListener("click", () => {
  resultContainer.classList.add("hidden");
  buttonContainer.classList.remove("hidden");
});

// 根据爻象模式更新卦象
function updateGuaByPattern(pattern) {
  // 获取所有爻线元素 (从上到下)
  const yaos = document.querySelectorAll(".yao");

  // 按顺序更新爻线
  yaos.forEach((yao, index) => {
    const isYang = pattern[index] === 1;

    // 添加动画效果
    yao.classList.add("yao-animation");

    setTimeout(() => {
      if (isYang) {
        // 阳爻 - 完整线
        yao.innerHTML = `
                    <span class="zuo w-1/2 h-full bg-neutral"></span>
                    <span class="you w-1/2 h-full bg-neutral"></span>
                `;
        yao.classList.remove("bg-neutral/20");
        yao.classList.add("bg-neutral/80");
      } else {
        // 阴爻 - 断线
        yao.innerHTML = `
                    <span class="zuo w-1/2 h-full bg-neutral"></span>
                    <span class="you w-1/2 h-full bg-transparent"></span>
                `;
        yao.classList.remove("bg-neutral/80");
        yao.classList.add("bg-neutral/20");
      }

      // 移除动画类
      yao.classList.remove("yao-animation");
    }, 300);
  });
}

// 模拟掷铜钱过程并更新卦象
function simulateCoinTossing() {
  // 生成随机卦象
  const randomHexagram =
    hexagrams[Math.floor(Math.random() * hexagrams.length)];
  const yaos = document.querySelectorAll(".yao");
  const totalSteps = 18; // 每爻模拟3次掷钱，共6爻
  let currentStep = 0;

  // 重置所有爻为初始状态
  yaos.forEach((yao) => {
    yao.innerHTML = `
            <span class="zuo w-1/2 h-full bg-neutral/40"></span>
            <span class="you w-1/2 h-full bg-neutral/40"></span>
        `;
    yao.classList.remove("bg-neutral/20", "bg-neutral/80");
    yao.classList.add("bg-neutral/40");
  });

  // 模拟掷钱动画
  const interval = setInterval(() => {
    const currentYaoIndex = Math.floor(currentStep / 3);
    const currentYao = yaos[currentYaoIndex];

    // 随机改变爻的状态，但最终会趋向于真实结果
    const randomness = Math.random();
    const isYang = randomness < 0.5 ? 0 : 1;

    currentYao.innerHTML = `
            <span class="zuo w-1/2 h-full ${
              isYang ? "bg-neutral" : "bg-neutral/40"
            }"></span>
            <span class="you w-1/2 h-full ${
              isYang ? "bg-neutral" : "bg-neutral/40"
            }"></span>
        `;

    currentYao.classList.remove(
      "bg-neutral/20",
      "bg-neutral/80",
      "bg-neutral/40"
    );
    currentYao.classList.add(isYang ? "bg-neutral/80" : "bg-neutral/40");

    // 添加闪烁动画
    currentYao.classList.add("yao-flash");
    setTimeout(() => {
      currentYao.classList.remove("yao-flash");
    }, 200);

    currentStep++;

    // 完成所有步骤后，确定最终卦象
    if (currentStep >= totalSteps) {
      clearInterval(interval);

      // 延迟显示最终结果
      setTimeout(() => {
        // 根据卦象更新爻线
        updateGuaByPattern(randomHexagram.yaoPattern);

        // 更新右侧结果区域
        resultContainer.innerHTML = `
                    <div class="hexagram-card mb-6">
                        <h3 class="text-lg font-semibold mb-4 flex items-center">
                            <i class="fa fa-info-circle mr-2 text-secondary"></i>
                            卜算结果
                        </h3>
                        
                        <div class="flex justify-between items-center mb-4">
                            <div>
                                <p class="hexagram-title" id="result-gua-name">${
                                  randomHexagram.name
                                }</p>
                                <p class="hexagram-desc" id="result-gua-desc">${
                                  randomHexagram.description
                                }</p>
                            </div>
                            <div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center">
                                <i class="fa fa-yelp text-primary text-xl"></i>
                            </div>
                        </div>
                        
                        <div class="border-t border-gray-100 pt-4">
                            <h4 class="font-medium mb-2">卦辞</h4>
                            <p class="hexagram-text" id="result-gua-text">${
                              randomHexagram.text
                            }</p>
                        </div>
                        
                        <div class="mt-4 pt-4 border-t border-gray-100">
                            <h4 class="font-medium mb-2">爻辞解析</h4>
                            <div id="yao-analysis" class="space-y-2">
                                ${randomHexagram.yaoTexts
                                  .map(
                                    (text, index) => `
                                    <p class="yao-text">${getYaoPositionText(
                                      randomHexagram.yaoPattern[index],
                                      index
                                    )}: ${text}</p>
                                `
                                  )
                                  .join("")}
                            </div>
                        </div>
                    </div>
                    
                    <button id="new-calculate" class="w-full py-3 px-6 bg-secondary text-white rounded-xl shadow-md btn-hover">
                        <i class="fa fa-refresh mr-2"></i>重新卜算
                    </button>
                `;

        // 更新左侧卦名和卦辞
        updateGuaInfo(randomHexagram);

        // 重新绑定事件
        document
          .getElementById("new-calculate")
          .addEventListener("click", () => {
            resultContainer.classList.add("hidden");
            buttonContainer.classList.remove("hidden");
          });
      }, 1000);
    }
  }, 200);
}

// 获取爻的位置文本
function getYaoPositionText(isYang, index) {
  // 0-5 对应爻的位置，1表示阳爻，0表示阴爻
  const positions = [
    ["初六", "初九"],
    ["六二", "九二"],
    ["六三", "九三"],
    ["六四", "九四"],
    ["六五", "九五"],
    ["上六", "上九"],
  ];
  return positions[index][isYang ? 1 : 0];
}

// 更新卦名和卦辞
function updateGuaInfo(hexagram) {
  if (!hexagram) return;

  // 更新左侧卦名区域
  guaInfo.innerHTML = `
        <h3 class="hexagram-title">${hexagram.name}</h3>
        <p class="hexagram-desc">${hexagram.description}</p>
        <div class="border-t border-gray-100 pt-3">
            <p class="hexagram-text">${hexagram.text}</p>
        </div>
    `;

  // 如果结果区域已显示，也更新它
  if (!resultContainer.classList.contains("hidden")) {
    document.getElementById("result-gua-name").textContent = hexagram.name;
    document.getElementById("result-gua-desc").textContent =
      hexagram.description;
    document.getElementById("result-gua-text").textContent = hexagram.text;

    // 更新爻辞解析
    const yaoAnalysis = document.getElementById("yao-analysis");
    if (yaoAnalysis) {
      yaoAnalysis.innerHTML = hexagram.yaoTexts
        .map(
          (text, index) => `
                <p class="yao-text">${text}</p>
            `
        )
        .join("");
    }
  }
}

// 根据爻象模式查找对应的卦
function findHexagramByPattern(pattern) {
  // 将模式转换为字符串以便比较
  const patternStr = pattern.join("");

  // 在64卦数据中查找匹配的卦
  return (
    hexagrams.find((hexagram) => {
      const hexPatternStr = hexagram.yaoPattern.join("");
      return hexPatternStr === patternStr;
    }) || hexagrams[0]
  ); // 默认返回乾为天
}
